package com.example.administrator.printoutindemo;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.example.administrator.printoutindemo.adapter.LocationAdapter;
import com.example.administrator.printoutindemo.base.BaseActivity;
import com.example.administrator.printoutindemo.bean.LocationBean;
import com.example.administrator.printoutindemo.http.SPUtil;
import com.example.administrator.printoutindemo.view.MyImageButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.SharedPreferencesHelper;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.zhinenghuacangku.mvp.ui.activity.ScanQRCodeActivity;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;

/**
 * Created by Administrator on 2018/9/11.
 */

public class OutStoreLocationActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, LocationAdapter.ChuKuSuccess {

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;
    private ListView lv_xmqd;
    private List<LocationBean> mlist = new ArrayList<>();
    private LocationAdapter mAdapter;
    private MyImageButton mimb_scan;
    private ImageView iv_back;
    private ImageView btnRight;
    private String scanResult = "";
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_outstorelocation);
        ButterKnife.bind(this);
        initEmpty();
        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.chu_ku));
        lv_xmqd = (ListView) findViewById(R.id.lv_xmqd);
        mimb_scan = (MyImageButton) findViewById(R.id.mimb_scan);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        btnRight = (ImageView) findViewById(R.id.btnRight);
        mAdapter = new LocationAdapter(OutStoreLocationActivity.this, mlist, this, mSharedPreferencesHelper);
        lv_xmqd.setAdapter(mAdapter);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_scan));
        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                new IntentIntegrator(OutStoreLocationActivity.this)
//                        .setOrientationLocked(false)
//                        .setCaptureActivity(ScanActivity.class)
//                        .initiateScan();
//                Intent openCameraIntent = new Intent(OutStoreLocationActivity.this, CaptureActivity.class);
                if (getPermission()) {
                    toScanQRCodeActivity();
                }

            }
        });
        getOutStorageDetail();
    }

    private void initEmpty() {
        empty_image.setImageResource(com.xiaoxing.zhinenghuacangku.R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的照相使用权限", 103, permissions);
            return false;
        }

    }

    private void toScanQRCodeActivity() {
        Intent openCameraIntent = new Intent(OutStoreLocationActivity.this, ScanQRCodeActivity.class);
        SharedPreferencesHelper mSharedPreferencesHelper = SharedPreferencesHelper.getInstance(OutStoreLocationActivity.this);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
        startActivityForResult(openCameraIntent, 101);
    }

    private void getOutStorageDetail() {

        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);

        String methodName = "GetOutStorageDetail";

        lv_xmqd.setVisibility(View.GONE);
        mEmptyLayout.setVisibility(View.VISIBLE);

        SoapParams params = new SoapParams();
        params.put("batchId", SPUtil.getString(OutStoreLocationActivity.this, "batchid", ""));


        /**
         * 请求
         */
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                LoadingDialogUtil.dismissDialog();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    List<LocationBean> outKuListBeen = new Gson().fromJson(result, new TypeToken<List<LocationBean>>() {
                    }.getType());
                    if (outKuListBeen != null && outKuListBeen.size() > 0) {
                        mEmptyLayout.setVisibility(View.GONE);
                        lv_xmqd.setVisibility(View.VISIBLE);
                        mAdapter.addAll(outKuListBeen);
                    } else {
                        mEmptyLayout.setVisibility(View.VISIBLE);
                        lv_xmqd.setVisibility(View.GONE);
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                LoadingDialogUtil.dismissDialog();
                ArmsUtils.makeText(getContext(), error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                LoadingDialogUtil.dismissDialog();

            }
        }, getAapiUserName(), getApiPwd());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
//        Log.e("99999999=====",intentResult.getContents());
//        if (intentResult!=null) {
        if (resultCode == 101) {
            Bundle bundle = data.getExtras();
            scanResult = bundle.getString("scan_result");
            String h = scanResult;
            SPUtil.putString(OutStoreLocationActivity.this, "newmidss", h);
            setIsScan(scanResult);
        } else {
            SPUtil.putString(OutStoreLocationActivity.this, "newmidss", "");
        }

    }

    /**
     * 设置是否扫描
     *
     * @param mid
     */
    private void setIsScan(String mid) {
        for (int k = 0; k < mlist.size(); k++) {
            LocationBean locationBean = mlist.get(k);
            // 不全选中
            if (locationBean.getMid().equals(mid)) {
                locationBean.setIsScan("1");
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
            toScanQRCodeActivity();
        }
    }

    @Override
    public void refreshData() {
        getOutStorageDetail();
    }
}
